package org.tity.test.dao.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tity.sql.dao.DAO;
import org.tity.test.config.AppDAO;

@Service
//@Transactional
public class TransactionService {

	@Autowired
	private DAO dao;
	
	public String t1()
	{
		//如果任意一个语句异常，则整个事务失败
		dao.multiExecute("delete from trans where code='001'","delete from trans where codex='002'");
//		t2();
//		dao.beginTransaction();
//		dao.execute("delete from trans where code='001'");
//		dao.execute("delete from trans where codex='002'");
		
		return "OK";
	}
	
	@Transactional
	public String t2()
	{
		dao.beginTransaction();
//		dao.execute("delete from trans where code='001'");
//		dao.execute("delete from trans where codex='002'");
		t3();
		return "OK";
	}
	
	@Transactional(AppDAO.TRANSACTION_MANAGER)
	public String t3()
	{
		dao.execute("delete from trans where code='001'");
		dao.execute("delete from trans where codex='002'");
		return "OK";
	}
	
	@Transactional("XXX")  //异常 No bean named 'XXX' available: No matching PlatformTransactionManager bean found for qualifier 'XXX' - neither qualifier match nor bean name match!
	public String t4()
	{
		dao.execute("delete from trans where code='001'");
		dao.execute("delete from trans where codex='002'");
		return "OK";
	}
	
	
 
	public String t5(int i)
	{
		dao.beginTransaction();
		dao.execute("update trans set name=?  where code='118'","118:"+System.currentTimeMillis());
		if(i==1) dao.rollback(); //回滚
		if(i==2) dao.commit(); //回滚
 
		//其它值，锁表
		 
		return "OK";
	}
	
	
	@Transactional(AppDAO.TRANSACTION_MANAGER)
	public String te1(String act) throws Exception
	{
		if(act==null) act="none";
		
		dao.execute("update trans set name=?  where code='119'",act+":"+System.currentTimeMillis());
		
		if(act.equals("checked"))
		{
			//事务不回滚
			throw new Exception("异常"); 
		}
		
		if(act.equals("unchecked"))
		{
			//事务回滚
			throw new RuntimeException("异常");
		}
		
		return "OK";
	}
	

	@Transactional(transactionManager=AppDAO.TRANSACTION_MANAGER,rollbackFor= {Exception.class},noRollbackFor= {RuntimeException.class})
	public String te2(String act) throws Exception
	{
		if(act==null) act="none";
		
		dao.execute("update trans set name=?  where code='119'",act+":"+System.currentTimeMillis());
		
		if(act.equals("checked"))
		{
			//事务回滚
			throw new Exception("异常");
		}
		
		if(act.equals("unchecked"))
		{
			//事务不回滚
			throw new RuntimeException("异常");
		}
		
		return "OK";
	}
	
}
